<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>首页</title>
    <link rel="stylesheet" href="../lib/css/bootstrap.min.css" />
    <script src="../lib/js/jquery-3.3.1.min.js"></script>
    <script src="../lib/js/bootstrap.min.js"></script>
    <script src="../lib/js/thingjs.min-v1.2.2.4.js"></script>
    <script src="../lib/js/thing.widget.min.js"></script>

    <style>
        html, body{
            width: 100%;
            height: 100%;
            margin: 0;
            padding: 0;
            overflow: hidden;
        }
        header{
            position:absolute;
            z-index:99;
            width:100%;
            background-color: white
        }

    </style>
</head>
<body>
<!--导航栏-->
<div id="3d">
    <header>
        <div class="row model">
            <div class="col-md-3">
                <div style="height: 50px;line-height: 50px;">
                    <a href="/index"><img width="200px" height="50px" src="../imgs/logo2x.png"></a>
                </div>
            </div>

            <div class="col-md-9">
                <div class="row">
                    <div class="col-md-9" style="line-height: 50px">
                        <!--themleaf页面传递参数-->
                        <h1>[[${scene.sName}]]</h1>
                    </div>
                    <div class="col-md-3" style="line-height: 50px">
                        <a href="/index"><img height="30px" src="../imgs/close.png"></a>
                    </div>
                </div>
            </div>
        </div>
    </header>
</div>

</body>
<script>
    //加载场景
    app = new THING.App({
        container	: '3d',
        url			: './scene',
    });

    app.on('load', function (ev) {
        var floor = app.query('.Building')[0].floors[0];                                    //建筑内楼层
        app.level.change(floor);                                                  //进入建筑层级
        app.pauseEvent(THING.EventType.Click, '*', THING.EventTag.LevelBackMethod);         //暂停单击返回上一层级功能

        app.on(THING.EventType.DBLClick, function(ev) {                                     // 双击右键回到上一层级
            if (ev.button !== 2) {
                return;
            }
            app.level.back();
        }, 'customLevelBackMethod');

        //初始化工具面板
        init_cabinets();                                                                 //初始化机柜
        init_toolPanel();


    });

    // 机柜相关
    const CABINET_DEFAULT_UNITCOUNT = 42; // 默认机柜u数
    const RACK_UNIT_HEIGHT = 0.0445; // 1u为4.3厘米
    const BarGraphColors = ['#0000ff', '#00ffff', '#00ff00', '#ff0000', '#ff00ff', '#ffff00'];

    /**
     * Cabinet 机柜类
     */
    class Cabinet extends THING.Thing {
        constructor(app) {
            super(app);
            this.racks = [];
            this.isCabinet = true;
            this.barGraph = null;
            this.ui = null;
            this.number = Math.randomInt(100, 300);
        }

        createRack(url, u) {
            var y = u * RACK_UNIT_HEIGHT;
            var cabinet = this;
            var rack = this.app.create({
                type: 'Rack',
                name: 'rack',
                url: url,
                complete: function() {
                    cabinet.add({
                        object: this,
                        basePoint: 'BasePoint',
                        localPosition: [0, y, 0],
                        localAngles: [0, 0, 0]
                    });

                }
            });
            return rack;
        }

        createRacks() {
            var curUPos = 0;
            while(true) {
                var pair = RackModels[Math.randomInt(0, RackModels.length - 1)];
                var url = pair[0];
                var uHeight = pair[1];

                var rack = this.createRack(url, curUPos);
                this.racks.push(rack);

                if (curUPos >= CABINET_DEFAULT_UNITCOUNT - 4)
                    break;

                curUPos += uHeight;
            }
            return rack;
        }

        destroyRacks() {
            for (var i = 0; i < this.racks.length; i ++) {
                var rack = this.racks[i];
                rack.destroy();
            }
            this.racks = [];
        }

        openDoor() {
            this.playAnimation('open1');
            this.createRacks();
        }

        closeDoor() {
            this.playAnimation({
                name: 'close1',
                complete: function() {
                    this.destroyRacks();
                    if (Rack.current)
                        Rack.current.showUI(false);
                }
            });
        }

        // 创建柱状图
        createBarGraph() {
            if (this.barGraph)
                return;

            var box = app.create({
                type: 'Box',
                width: this.size[0] * 0.9,
                height: this.size[1],
                depth: this.size[2] * 0.9,
                position: this.position,
                center: 'Bottom'
            });

            this.barGraph = box;
        }

        // 显示柱状图
        showBarGraph(bool) {
            if (bool) {
                // 确认创建了盒子
                this.createBarGraph();
                // 隐藏机柜，显示盒子
                this.visible = false;
                this.barGraph.visible = true;
                this.barGraph.style.color = Math.randomFromArray(BarGraphColors);
                //this.barGraph.style.opacity = 0.9;
                // 缩放盒子
                this.barGraph.scale = [1, 0.1, 1];
                this.barGraph.scaleTo({
                    scale: [1, Math.randomFloat(0.2, 1.0), 1],
                    time: 400,
                    lerpType: THING.LerpType.Linear.Quadratic
                });
            } else {
                // 隐藏盒子，显示机柜
                this.visible = true;
                if (this.barGraph)
                    this.barGraph.visible = false;
            }
        }

        // 创建界面
        createUI() {
            if (this.ui)
                return;
            var cabinet = this;

            // 创建widget (动态绑定数据用)
            var panel = new THING.widget.Panel({
                width: "110px",
                closeIcon: false,
                opacity: 0.8,
            });
            this.panel = panel;
            panel.addString(this, 'name').name('机柜'+this.number);

            // 创建obj ui (跟随物体用)
            var ui = app.create({
                type: 'UI',
                parent: this,
                el: panel.domElement,
                offset: [0, cabinet.size[1], 0]
            });
            this.ui = ui;
        }

        // 显示界面
        showUI(boolValue) {
            if (!this.ui)
                this.createUI();

            this.panel.visible = boolValue;
        }
    }
    THING.factory.registerClass('Server', Cabinet);
    Cabinet.current = null;
    Cabinet.open = false;

    // 架式设备模型
    const RackModels = [
        ['http://model.3dmomoda.cn/models/3817338017ff4776a5dd05f03a3e2fd4/0/gltf', 1],
        ['http://model.3dmomoda.cn/models/37972dd2c96c4a37a3245a00bee3628b/0/gltf', 2]
    ];

    /**
     * Rack 架式设备
     */
    class Rack extends THING.Thing {
        constructor(app) {
            super(app);
            this.isRack = true;
            this.info = gen_rack_info();
        }

        createUI() {
            var ui = new THING.widget.Panel({
                titleText: this.name,
                closeIcon: true,
                dragable: true,
                retractable: true,
                hasTitle: true,
                width: "300px",
            });
            ui.zIndex = 999999;//设置ui排序
            ui.addTab(this.info);
            ui.position = [390, 350];
            this.ui = ui;
            return ui;
        }

        showUI(boolValue) {
            if (!this.ui)
                this.createUI();
            this.ui.show(boolValue);
        }
    }
    THING.factory.registerClass('Rack', Rack);
    Rack.current = null;

    function gen_rack_info() {
        var type2 = ["PC服务器", "路由器"];
        var type3 = ["IBM", "HP", "DELL"];
        var people = ["王WW", "李LL", "张ZZ"];
        var info = {
            "基本信息": {
                "一级分类": "微机",
                "二级分类": type2[Math.randomInt(0,1)],
                "设备类型": type3[Math.randomInt(0,2)],
                "编号": "00" + Math.randomInt(0, 9),
                "使用人": people[Math.randomInt(0,2)],
                "管理员": people[Math.randomInt(0,2)],
                "上架时间": ""+Math.randomInt(10,23)+":"+Math.randomInt(10,23),
            },
            "扩展信息": {
                "信息XX": Math.ceil(Math.random() * 27 + 25) + "",
                "信息YY": Math.ceil(Math.random() * 25 + 20) + "",
                "信息ZZ": Math.ceil(Math.random() * 27 + 25) + "",
                "信息AA": Math.ceil(Math.random() * 25 + 20) + "",
                "信息BB": Math.ceil(Math.random() * 27 + 25) + "",
                "信息CC": Math.ceil(Math.random() * 25 + 20) + "",
                "信息DD": Math.ceil(Math.random() * 25 + 20) + "",
            }
        };
        return info;
    }

    // 初始化机柜
    function init_cabinets() {
        var cabinets = app.query('.Cabinet');

        // 双击左键开门
        cabinets.on('dblclick', function() {

            // 摄影机飞行
            var pos = this.selfToWorld([0, 2.0, 2.1]);
            //var pos = this.selfToWorld([-0.6, 1.1, 2.3]);
            var targ = this.position;
            targ[1] += 0.95;
            app.camera.flyTo({
                time: 1000,
                position: pos,
                target: targ,
            });

            // 机柜开门动画
            if (Cabinet.current) {
                Cabinet.current.closeDoor();
                Cabinet.current = null;
            }
            this.openDoor();

            // 设置为当前
            Cabinet.current = this;
            this.style.outlineColor = null; // 当前机柜不沟边
        })

        // 右键关门
        app.on('click', function(event) {
            if (event.button == 2) {
                if (Cabinet.current) {
                    Cabinet.current.closeDoor();
                    Cabinet.current = null;
                } else {
                    // 如果没有当前机柜则飞到一个最佳位置
                    app.camera.flyTo({
                        time: 1500,
                        position: [-10.4, 13.6, 12.3],
                        target: [3.6, -4, -1.7],
                    });
                }
            }
        });

        // 机柜 滑过沟边
        cabinets.on('mouseon', function () {
            if (this != Cabinet.current) {
                this.style.outlineColor = '#00ff00';
                this.showUI(true);
            }
        });
        cabinets.on('mouseoff', function () {
            this.style.outlineColor = null;
            this.showUI(false);
        });

        // 架式服务器事件（尚未创建，预先注册）
        app.on('mouseon', '.Rack', null, function (ev) {
            this.style.outlineColor = '#ff0000';
        });
        app.on('mouseoff', '.Rack', null, function (ev) {
            this.style.outlineColor = null;
        });
        app.on('click', '.Rack', null, function (ev) {
            if (Rack.current == this)
                return;

            if (Rack.current) {
                Rack.current.showUI(false);
                Rack.current = null;
            }
            Rack.current = this;
            this.showUI(true);
        });
    }



    function init_toolPanel(){
        var panel = new THING.widget.Panel({
            //面板位置
            position: [300,1800],
            // 模板样式
            template: "default",
            // 角标样式
            cornerType: "none",
            // 父节点设置，默认为document.body
            parent: document.body,
            // 设置面板宽度
            width: "90",
            // 是否允许有面板title
            hasTitle: false,
            // 设置title图标
            titleImage: "icon.png",
            // title是否允许有关闭按钮
            closeIcon: false,
            // title是否支持拖拽功能
            dragable: false,
            // title是否支持收起功能
            retractable: false,
            // 设置透明度
            opacity: 0.9,
            // 设置层级
            zIndex: 99
        });


        //设置面板中的数据
        var dataObj = {
            space: false,           //空间统计
            monitor: false,         //视频监控
            ring: false,            //动环
            statistics: false,      //承重统计
            assets: false           //资产
        }

        var img0 = panel.addImageBoolean(dataObj, 'space').caption('空间统计').url('../imgs/space.png');
        var img1 = panel.addImageBoolean(dataObj, 'monitor').caption('视频监控').url('../imgs/monitor.png');
        var img2 = panel.addImageBoolean(dataObj, 'ring').caption('动环').url('../imgs/ring.png');
        var img3 = panel.addImageBoolean(dataObj, 'statistics').caption('承重统计').url('../imgs/statistics.png');
        var img4 = panel.addImageBoolean(dataObj, 'assets').caption('资产').url('../imgs/assets.png');

        //给图标绑定事件
        img0.on('change', function(boolValue) {
            onChangeImageButton('space',boolValue);
        });
        img1.on('change', function(boolValue) {onChangeImageButton('monitor',boolValue);});
        img2.on('change', function(boolValue) {onChangeImageButton('ring',boolValue);});
        img3.on('change', function(boolValue) {onChangeImageButton('statistics',boolValue);});
        img4.on('change', function(boolValue) {onChangeImageButton('assets',boolValue);});
    }

    //处理工具条按钮
    function onChangeImageButton(key, boolValue) {
            console.log(boolValue);
            if(key === "space"){
                app.query('.Cabinet').forEach(function (obj) {               //进行空间统计

                    obj.showBarGraph(boolValue);
                })
            }



    }








</script>

</html>